<template>
    <view class="container">
        <view class="post-comment">
            <view class="goods">
                <view class="img">
                    <image :src="topic.picUrl"></image>
                </view>
                <view class="info">
                    <view class="t">
                        <text class="name">{{ topic.title }}</text>
                    </view>
                    <view class="attr">{{ topic.subtitle }}</view>
                </view>
            </view>
            <view class="rater">
                <text class="rater-title">评分</text>
                <block v-for="(item, index) in stars" :key="index">
                    <van-icon name="star" @tap.native="selectRater" color="#ab956d" :data-star="item" v-if="item < star" />

                    <van-icon name="star-o" @tap.native="selectRater" :data-star="item" v-else />
                </block>
                <text class="rater-desc">{{ starText }}</text>
            </view>
            <view class="input-box">
                <textarea class="content" :focus="true" @input="bindInputValue" maxlength="140" placeholder="留言经过筛选后，对所有人可见" />
                <text class="count">{{ 140 - content.length }}</text>
            </view>

            <view class="weui-uploader">
                <view class="weui-uploader__hd">
                    <view class="weui-uploader__title">图片上传</view>
                    <view class="weui-uploader__info">{{ picUrls.length }}/{{ files.length }}</view>
                </view>
                <view class="weui-uploader__bd">
                    <view class="weui-uploader__files" id="uploaderFiles">
                        <block v-for="(item, index) in files" :key="index">
                            <view class="weui-uploader__file" @tap="previewImage" :id="item">
                                <image class="weui-uploader__img" :src="item" mode="aspectFill" />
                            </view>
                        </block>
                        <view class="weui-uploader__input-box">
                            <view class="weui-uploader__input" @tap="chooseImage"></view>
                        </view>
                    </view>
                </view>
            </view>

            <view class="btns">
                <view class="close" @tap="onClose">取消</view>
                <view class="post" @tap="onPost">发表</view>
            </view>
        </view>
    </view>
</template>

<script>
// 上传组件 基于https://github.com/Tencent/weui-wxss/tree/master/src/example/uploader
var app = getApp();

var util = require('../../utils/util.js');

var api = require('../../config/api.js');

export default {
    data() {
        return {
            valueId: 0,
            topic: {
                picUrl: '',
                title: '',
                subtitle: ''
            },
            content: {
                length: 0
            },
            stars: [0, 1, 2, 3, 4],
            star: 5,
            starText: '十分满意',
            hasPicture: false,
            picUrls: [],
            files: []
        };
    },
    onLoad: function (options) {
        if (parseInt(options.type) !== 1) {
            return;
        }

        var that = this;
        that.setData({
            valueId: options.valueId
        });
        this.getTopic();
    },
    onReady: function () {},
    onShow: function () {
        // 页面显示
    },
    onHide: function () {
        // 页面隐藏
    },
    onUnload: function () {
        // 页面关闭
    },
    methods: {
        chooseImage: function (e) {
            if (this.files.length >= 5) {
                util.showErrorToast('只能上传五张图片');
                return false;
            }

            var that = this;
            uni.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success: function (res) {
                    that.setData({
                        files: that.files.concat(res.tempFilePaths)
                    });
                    that.upload(res);
                }
            });
        },

        upload: function (res) {
            var that = this;
            const uploadTask = uni.uploadFile({
                url: api.StorageUpload,
                filePath: res.tempFilePaths[0],
                name: 'file',
                success: function (res) {
                    var _res = JSON.parse(res.data);

                    if (_res.errno === 0) {
                        var url = _res.data.url;
                        that.picUrls.push(url);
                        that.setData({
                            hasPicture: true,
                            picUrls: that.picUrls
                        });
                    }
                },
                fail: function (e) {
                    uni.showModal({
                        title: '错误',
                        content: '上传失败',
                        showCancel: false
                    });
                }
            });
            uploadTask.onProgressUpdate((res) => {
                console.log('上传进度', res.progress);
                console.log('已经上传的数据长度', res.totalBytesSent);
                console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend);
            });
        },

        previewImage: function (e) {
            uni.previewImage({
                current: e.currentTarget.id,
                // 当前显示图片的http链接
                urls: this.files // 需要预览的图片http链接列表
            });
        },

        selectRater: function (e) {
            var star = e.currentTarget.dataset.star + 1;
            var starText;

            if (star == 1) {
                starText = '很差';
            } else {
                if (star == 2) {
                    starText = '不太满意';
                } else {
                    if (star == 3) {
                        starText = '满意';
                    } else {
                        if (star == 4) {
                            starText = '比较满意';
                        } else {
                            starText = '十分满意';
                        }
                    }
                }
            }

            this.setData({
                star: star,
                starText: starText
            });
        },

        getTopic: function () {
            let that = this;
            util.request(api.TopicDetail, {
                id: that.valueId
            }).then(function (res) {
                if (res.errno === 0) {
                    that.setData({
                        topic: res.data.topic
                    });
                }
            });
        },

        onClose: function () {
            uni.navigateBack();
        },

        onPost: function () {
            let that = this;

            if (!this.content) {
                util.showErrorToast('请填写评论');
                return false;
            }

            util.request(
                api.CommentPost,
                {
                    type: 1,
                    valueId: that.valueId,
                    content: that.content,
                    star: that.star,
                    hasPicture: that.hasPicture,
                    picUrls: that.picUrls
                },
                'POST'
            ).then(function (res) {
                if (res.errno === 0) {
                    uni.showToast({
                        title: '评论成功',
                        complete: function () {
                            uni.navigateBack();
                        }
                    });
                }
            });
        },

        bindInputValue(event) {
            let value = event.detail.value; //判断是否超过140个字符

            if (value && value.length > 140) {
                return false;
            }

            this.setData({
                content: event.detail.value
            });
        }
    }
};
</script>
<style>
@import './topicCommentPost.css';
</style>
